package com.example.shoppingmall.cotroller;

import com.alibaba.fastjson.JSONArray;
import com.example.shoppingmall.pojo.*;
import com.example.shoppingmall.service.*;
import com.example.shoppingmall.service.sms.SMSCode_no;
import com.example.shoppingmall.service.sms.SMSCode_refund;
import com.example.shoppingmall.service.sms.SMSCode_register;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
//@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    PaymentService paymentService;
    @Autowired
    PayMethodService payMethodService;
    @Autowired
    WithdrawalService withdrawalService;
    @Autowired
    ReturnService returnService;
    @Autowired
    AccountService accountService;
    @Autowired
    private SMSCode_refund smsCode_refund;
    @Autowired
            private NoteService noteService;
    @Autowired
    private SMSCode_no smsCode_no;


    List<Withdrawal> withList = new ArrayList<>();
    List<Examine> exList = new ArrayList<>();
    List<PayMethod> metList = new ArrayList<>();
    List<MetState> staList = new ArrayList<>();
    List<Payment> payList = new ArrayList<Payment>();
    List<PayType> typeList = new ArrayList<PayType>();
    List<Return> retList = new ArrayList<>();
    List<Rrturnstatus> rrtList = new ArrayList<>();
    List<Returnmethod> remList = new ArrayList<>();
    List<Account> accList = new ArrayList<>();
    List<AccType> actyList = new ArrayList<>();

    Integer bill_typeIds = null;

    /**
     * 支付单列表查询
     * @param bill_id
     * @param third_id
     * @param userPhone
     * @param currentPage
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/paylist")
    public String toPaylist(@RequestParam(value="bill_id",required = false)Integer bill_id, @RequestParam(value="third_id",required = false)Integer third_id,
                            @RequestParam(value="userPhone",required = false)String userPhone,
                            @RequestParam(value="currentPage",required = false)Integer currentPage, Model model, HttpSession session){
        if(session.getAttribute("typeList")==null){
            typeList = paymentService.getPayType();
            session.setAttribute("typeList",typeList);
        }

        Pages page = new Pages();
        Integer total = paymentService.total(bill_id,third_id,userPhone);
        page.setTotalPageCount(total);
        if(currentPage==null || currentPage==0){
            page.setCurrentPage(1);
        }else{
            page.setCurrentPage(currentPage);
        }
        Integer pageNo = (page.getCurrentPage()-1)*page.getPageSize();
        payList = paymentService.payList(bill_id,third_id,userPhone,pageNo,page.getPageSize());
        model.addAttribute("payList",payList);
        model.addAttribute("page",page);
        if(bill_id!=null){
            model.addAttribute("bill_id",bill_id);
        }
        if(third_id!=null) {
            model.addAttribute("third_id", third_id);
        }
        if(userPhone!=null) {
            model.addAttribute("userPhone", userPhone);
        }
        return "manage/bill_payments";
    }

    /**
     * 查询支付详情
     * @param bill_id
     * @return
     */
    @RequestMapping("/getPay")
    @ResponseBody
    public Object getPay(@RequestParam(value="bill_id")Integer bill_id){
        Map<String,Object> map = new HashMap<>();
        Payment payment = paymentService.getPay(bill_id);
        map.put("payment",payment);
        return map;
    }

    String wuserPhone=null;
    Integer wex_id=null;
    /**
     * 提现列表
     * @param userPhone
     * @param ex_id
     * @param currentPage
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/withdlist")
    public String withdlist(@RequestParam(value="userPhone",required = false)String userPhone, @RequestParam(value="ex_id",required = false)Integer ex_id,
                            @RequestParam(value="currentPage",required = false)Integer currentPage, Model model, HttpSession session){
        if(session.getAttribute("exList")==null){
            exList = withdrawalService.exList();
            session.setAttribute("exList",exList);
        }
        if(ex_id!=null){
            wex_id = ex_id;
        }
        ex_id = wex_id;
        if(ex_id==null){
            ex_id=0;
        }
        Pages page = new Pages();
        Integer total = withdrawalService.total(userPhone,ex_id);
        page.setTotalPageCount(total);
        if(currentPage==null || currentPage==0){
            page.setCurrentPage(1);
        }else{
            page.setCurrentPage(currentPage);
        }
        Integer pageNo = (page.getCurrentPage()-1)*page.getPageSize();
        withList = withdrawalService.getWithd(userPhone,ex_id,pageNo,page.getPageSize());
        model.addAttribute("withList",withList);
        model.addAttribute("page",page);
        if (userPhone != null){
            model.addAttribute("userPhone",userPhone);
        }
        if (ex_id != null){
            model.addAttribute("ex_id",ex_id);
        }
        return "manage/balance";
    }

    /**
     * 查看详情
     * @param id
     * @return
     */
    @RequestMapping("/getWithdrawal")
    @ResponseBody
    public Object getWithdrawal(@RequestParam("id")Integer id){
        Map<Object,Object> map = new HashMap<>();
        Withdrawal withd = withdrawalService.getWithdrawal(id);
        if(withd!=null){
            map.put("withd",withd);
        }
        return JSONArray.toJSONString(map);
    }

    /**
     * 提现审核
     * @param ex_id
     * @param id
     * @return
     */
    @RequestMapping("/withUpdate")
    @ResponseBody
    public Object withUpdate(@RequestParam("ex_id")Integer ex_id,@RequestParam(value="userPhone",required = false)String userPhone,
            @RequestParam(value="account_name",required = false)String account_name,@RequestParam(value="money",required = false)Double money,@RequestParam(value="id",required = false)Integer id){
        Map<Object,Object> map = new HashMap<>();
        Withdrawal withdrawal = new Withdrawal();
        withdrawal.setEx_id(ex_id);
        withdrawal.setId(id);
        int result = withdrawalService.update(withdrawal);
        if(result>0){
            if(ex_id==2){
                User user = new User();
                Account account = new Account();
                account.setMoney(money);
                account.setUsername(account_name);
                account.setDescribe("提现了"+money+"元");
                account.setAcc_typeId(3);
                account.setUserPhone(userPhone);
                user.setUserBalance(money);
                user.setUsername(account_name);
                int users = accountService.userUpdate(user);
                User user1 = accountService.user1(account_name);
                /*User user2 = new User();
                User user3 = accountService.user2();
                user2.setUsername(user3.getUsername());
                user2.setUserBalance(money);
                int esu = accountService.userUpdate(user2);*/
                account.setUserBalance(user1.getUserBalance());
                int acc = accountService.retAdd(account);
            }
            map.put("status","Yes");
        }else{
            map.put("status","No");
        }
        return JSONArray.toJSONString(map);
    }

    String method_names = null;
    Integer method_states = null;
    /**
     * 支付方式列表
     * @param method_id
     * @param method_name
     * @param method_state
     * @param currentPage
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/metlist")
    public String metList(@RequestParam(value="method_id",required = false)Integer method_id,@RequestParam(value="method_name",required = false)String method_name, @RequestParam(value="method_state",required = false)Integer method_state,
                          @RequestParam(value="currentPage",required = false)Integer currentPage, Model model, HttpSession session){
        if(session.getAttribute("metlist")==null || session.getAttribute("staList")==null){
            staList = payMethodService.staList();
            session.setAttribute("staList",staList);
            metList = payMethodService.metList();
            session.setAttribute("metlist",metList);
        }
        if(method_name!=null){
            method_names = method_name;
        }
        method_name=method_names;
        if(method_state!=null){
            method_states = method_state;
        }
        method_state = method_states;
        if(method_state==null){
            method_state=0;
        }
        Pages page = new Pages();
        Integer total = payMethodService.total(method_name,method_state);
        page.setTotalPageCount(total);
        if(currentPage==null || currentPage==0){
            page.setCurrentPage(1);
        }else{
            page.setCurrentPage(currentPage);
        }
        Integer pageNo = (page.getCurrentPage()-1)*page.getPageSize();
        metList = payMethodService.getMethod(method_name,method_state,pageNo,page.getPageSize());
        model.addAttribute("metlist",metList);
        model.addAttribute("page",page);
        if(method_name!=null){
            model.addAttribute("method_name",method_name);
        }
        if(method_state!=null){
            model.addAttribute("method_state",method_state);
        }
        return "manage/payments";
    }

    /**
     * 获取支付方式的信息
     * @param method_id
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/getMet")
    public Object getMet(@RequestParam("method_id")Integer method_id,Model model,HttpSession session){
        if(session.getAttribute("staList")==null){
            staList = payMethodService.staList();
            session.setAttribute("staList",staList);
        }
        PayMethod method = payMethodService.getMet(method_id);
        model.addAttribute("method",method);
        return "manage/paymentsUpdate";
    }

    //修改状态开关
    /*@RequestMapping("/updateMet2")
    @ResponseBody
    public Object updateMet2(@RequestParam("method_state")Integer method_state,@RequestParam("method_id")Integer method_id){
        Map<Object,Object> map = new HashMap<>();
        PayMethod method = new PayMethod();
        method.setMch_id(method_id);
        method.setMethod_state(method_state);
        int result = payMethodService.updateMet2(method);
        map.put("method",method);
        return map;
    }*/

    /**
     * 对支付方式进行修改
     * @param app_id
     * @param private_key
     * @param public_key
     * @param method_sort
     * @param method_state
     * @param mch_id
     * @param key
     * @param certificate
     * @param method_id
     * @return
     */
    @RequestMapping("/metUpdate")
    public String metUpdate(@RequestParam(value="app_id",required = false)Integer app_id, @RequestParam(value="private_key",required = false)String private_key,
                            @RequestParam(value="public_key",required =false)String public_key, @RequestParam(value="method_sort",required = false)Integer method_sort,
                            @RequestParam(value="method_state",required = false)Integer method_state,@RequestParam(value="mch_id",required=false)Integer mch_id,
                            @RequestParam(value="key",required = false)String key,@RequestParam(value="certificate",required = false)String certificate,
                            @RequestParam(value="method_id",required=false)Integer method_id){
        PayMethod method = new PayMethod();
        if(method_id==1){
            method = new PayMethod();
            method.setApp_id(app_id);
            method.setPrivate_key(private_key);
            method.setPublic_key(public_key);
            method.setMethod_sort(method_sort);
            method.setMethod_state(method_state);
            method.setMethod_id(method_id);
            System.out.println();
            int result = payMethodService.updateMet(method);
            if(result>0){
//                return "redirect:/payment/metlist";
                return "redirect:/metlist";
            }else{
                return "manage/paymentsUpdate";
            }
        }else if(method_id==2){
            method = new PayMethod();
            method.setMch_id(mch_id);
            method.setMethod_sort(method_sort);
            method.setMethod_state(method_state);
            method.setMethod_id(method_id);
            int result = payMethodService.updateMet(method);
            if(result>0){
//                return "redirect:/payment/metlist";
                return "redirect:/metlist";
            }else{
                return "manage/paymentsUpdate";
            }
        }else if(method_id==3){
            method = new PayMethod();
            method.setMethod_state(method_state);
            method.setMethod_sort(method_sort);
            method.setMethod_id(method_id);
            int result = payMethodService.updateMet(method);
            if(result>0){
//                return "redirect:/payment/metlist";
                return "redirect:/metlist";
            }else{
                return "manage/paymentsUpdate";
            }
        }
        return "manage/payments";
    }

    Integer returnnos = null;
    String rphones = null;
    Integer rstatuss = null;
    /**
     * 退款单列表
     * @param returnno
     * @param rphone
     * @param rstatus
     * @param currentPage
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/retlist")
    public String retlist(@RequestParam(value="returnno",required = false)String returnno, @RequestParam(value="rphone",required = false)String rphone,
                          @RequestParam(value="rstatus",required = false)Integer rstatus,
                          @RequestParam(value="currentPage",required = false)Integer currentPage, Model model, HttpSession session){
        if(session.getAttribute("rrtList")==null || session.getAttribute("remList")==null){
            rrtList = returnService.getReSta();
            session.setAttribute("rrtList",rrtList);
            remList = returnService.getReMet();
            session.setAttribute("remList",remList);
        }
        if(rstatus!=null){
            rstatuss=rstatus;
        }
        rstatus=rstatuss;
        if(rstatus==null){
            rstatus=0;
        }
        User users=(User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = users.getUsername();
        Pages page = new Pages();
        Integer total = returnService.total(returnno,username,rphone,rstatus);
        page.setTotalPageCount(total);
        if(currentPage==null || currentPage==0){
            page.setCurrentPage(1);
        }else{
            page.setCurrentPage(currentPage);
        }
        Integer pageNo = (page.getCurrentPage()-1)*page.getPageSize();
        retList = returnService.getRet(returnno,username,rphone,rstatus,pageNo,page.getPageSize());
        model.addAttribute("retList",retList);
        model.addAttribute("page",page);
        if(returnno!=null){
            model.addAttribute("returnno",returnno);
        }
        if(rphone!=null){
            model.addAttribute("rphone",rphone);
        }
        if(rstatus!=null){
            model.addAttribute("rstatus",rstatus);
        }
        return "manage/bill_refund";
    }

    /**
     * 查看退款单详情
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/getRets")
    @ResponseBody
    public Object getRets(@RequestParam("id")Integer id,Model model){
        Map<Object,Object> map = new HashMap<>();
        Return aReturn = returnService.toRet(id);
        map.put("aReturn",aReturn);
        return map;
    }

    /**
     * 审核
     * @param rstatus
     * @param id
     * @return
     */
    @RequestMapping("/retUpdate")
    @ResponseBody
    public Object retUpdate(@RequestParam("rstatus")Integer rstatus,@RequestParam(value="rphone",required = false)String rphone,
            @RequestParam(value="rmoney",required = false)Double rmoney,@RequestParam(value="rphone1",required = false)String rphone1,@RequestParam(value="username",required = false)String username,@RequestParam(value="id",required = false)Integer id) throws Exception {
        Map<Object,Object> map = new HashMap<>();
        Return aReturn = new Return();
        aReturn.setRstatus(rstatus);
        aReturn.setId(id);
        int result = returnService.update(aReturn);
        if(result>0){
            if(rstatus==2){
//                //发短信
//                smsCode_refund.sendCode(rphone);
//                //存短信
//                Note note=new Note();
//                note.setPhone(rphone);
//                note.setTypeId(5);
//                note.setContentId(5);
//                noteService.add(note);
                User user = new User();
                Account account = new Account();
                account.setMoney(rmoney);
                account.setUsername(username);
                account.setDescribe("退款了"+rmoney+"元");
                account.setAcc_typeId(2);
                account.setUserPhone(rphone);
                account.setUserBalance(user.getUserBalance());
                user.setUserBalance(rmoney);
                user.setUsername(username);
                User user2 = accountService.user2();
                User user3= new User();
                user3.setUsername(user2.getUsername());
                user3.setUserBalance(rmoney);
                int us = accountService.userUpdate(user3);
                int users = accountService.userUpdateto(user);
                User user1 = accountService.user1(username);
                account.setUserBalance(user1.getUserBalance());
                int acc = accountService.retAddto(account);
            }
//            if(rstatus==3){
//                //发短信
//                smsCode_no.sendCode(rphone);
//                //存短信
//                Note note=new Note();
//                note.setPhone(rphone);
//                note.setTypeId(6);
//                note.setContentId(6);
//                noteService.add(note);
//            }
            map.put("status","Yes");
        }else{
            map.put("status","No");
        }
        return JSONArray.toJSONString(map);
    }

    String auserPhone = null;
    Integer aacc_typeId = null;
    /**
     * 账户资金管理
     */
    @RequestMapping("/acclist")
    public String retlist(@RequestParam(value="userPhone",required = false)String userPhone, @RequestParam(value="acc_typeId",required = false)Integer acc_typeId,
                          @RequestParam(value="currentPage",required = false)Integer currentPage, Model model, HttpSession session){
        if(session.getAttribute("actyList")==null){
            actyList = accountService.getAccTy();
            session.setAttribute("actyList",actyList);
        }
        if(acc_typeId!=null){
            aacc_typeId=acc_typeId;
        }
        acc_typeId=aacc_typeId;
        if(acc_typeId==null){
            acc_typeId=0;
        }
        Pages page = new Pages();
        Integer total = accountService.total(userPhone, acc_typeId);
        page.setTotalPageCount(total);
        if(currentPage==null || currentPage==0){
            page.setCurrentPage(1);
        }else{
            page.setCurrentPage(currentPage);
        }
        Integer pageNo = (page.getCurrentPage()-1)*page.getPageSize();
        accList = accountService.getAccList(userPhone,acc_typeId,pageNo,page.getPageSize());
        model.addAttribute("accList",accList);
        model.addAttribute("page",page);
        if(userPhone!=null){
            model.addAttribute("userPhone",userPhone);
        }
        if(acc_typeId != null){
            model.addAttribute("acc_typeId",acc_typeId);
        }
        return "manage/account_funds";
    }

}
